#include "user_info_request.h"

#include <iostream>
#include <sstream>
#include <string>
#include <map>

#include "base/logging.h"
#include "base/json_escape.h"
#include "im/common/common.h"
#include "im/adapters/recent_contact_adapter.h"

namespace imserver {
namespace fcgi {

bool UserInfoRequest::Response() {
  if (!fcgi_out_) {
    LOG_WARN("null fcgi_out!");
    return false;
  }

  ParseUserIdentity();

  UserProfile user_profile;
  int64_t qid = 0;
  try {
    qid = boost::lexical_cast<int64_t>(GetQuery("qid"));
  } catch (boost::bad_lexical_cast&) {}

  if (qid > 0 && qid < IM_TEMP_ID_BASE) {
    int res = UserProfileAdapter::Instance().Get(qid, &user_profile, 3);
    LOG_DEBUG("UserProfileAdapter::Get qid=" << qid << " res=" << res);
  } else {
    LOG_DEBUG("UserProfileAdapter::Get qid<=0!");
  }

  // 取在线状态
  SessionType::type session_type = SessionType::OFFLINE;
  if (qid > 0) {
    std::vector<int64_t> qids;
    qids.push_back(qid);
    std::map<int64_t, SessionType::type> online_map;
    SessionAdapter::Instance().GetOnlineUsers(qids, &online_map);
    std::map<int64_t, SessionType::type>::const_iterator it = online_map.find(qid);
    if (it != online_map.end()) {
      session_type = it->second;
    }
  }

  std::stringstream rsp_header;
  rsp_header << "Content-type: text/javascript; charset=utf-8\r\n" << "\r\n";
  FCGX_PutS(rsp_header.str().c_str(), fcgi_out_);

  std::stringstream rsp_body;
  std::string callback = ParseCallback();
  if (!callback.empty()) {
    // 开头空格是 IE bug fix
    rsp_body << ' ' << callback << "(";
  }
  if (user_profile.qid <= 0) {
    rsp_body << "{qid:" << qid
           << ",username:\"" << GetDefaultUsername(qid)
           << "\",head_pic:\"" << base::JsonEscape(kDefaultHeadPic)
           << "\",shop_name:\"\",shop_icon:\"\",shop_url:\"";
  } else {
    try {
    std::string url = user_profile.shop_url;
    size_t pos = url.find("bang.360.cn");
    if (pos > 0) {
      int32_t id = 0;
      try {
        id = boost::lexical_cast<int32_t>(url.substr(strlen("http://"), pos - strlen("http://")));
      } catch (boost::bad_lexical_cast) {} 
      if (id > 0) {
        user_profile.shop_url = url.substr(0, pos) + '.' + url.substr(pos);
      }
      LOG_INFO("urlfix " << url << "->" << user_profile.shop_url);
    }
    } catch (...) {
    }

    rsp_body << "{qid:" << user_profile.qid
           << ",username:\"" << base::JsonEscape(user_profile.username)
           << "\",head_pic:\"" << base::JsonEscape(user_profile.head_pic)
           << "\",shop_name:\"" << base::JsonEscape(user_profile.shop_name)
           << "\",shop_icon:\"" << base::JsonEscape(user_profile.shop_icon)
           << "\",shop_url:\"" << base::JsonEscape(user_profile.shop_url);
  }
  rsp_body << "\",online:" << session_type << "}";

  if (!callback.empty()) {
    rsp_body << ")";
  }

  LOG_DEBUG("UserInfoRequest uid=" << qid << " rsp=" << rsp_body.str());

  FCGX_PutS(rsp_body.str().c_str(), fcgi_out_);
  return true;
}

}
}


